package com.retail.lottery.colalottery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retail.lottery.colalottery.entity.MessageNoticeRecord;
import com.retail.lottery.colalottery.entity.NoticeTemplate;
import com.retail.lottery.colalottery.entity.OrderCallback;
import com.retail.lottery.colalottery.enums.MessageNoticeStatusEnum;
import com.retail.lottery.colalottery.enums.NoticeTypeEnum;
import com.retail.lottery.colalottery.service.MessageNoticeRecordService;
import com.retail.lottery.colalottery.mapper.MessageNoticeRecordMapper;
import com.retail.lottery.colalottery.service.NoticeTemplateService;
import com.retail.lottery.colalottery.service.cola.ColaClientService;
import com.retail.lottery.colalottery.vo.MessageNoticeVo;
import com.retail.lottery.colalottery.vo.response.GetSetupInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author jarvis.zhang
* @description 针对表【message_notice_record(消息通知记录表)】的数据库操作Service实现
* @createDate 2025-07-03 18:24:45
*/
@Service
@Slf4j
public class MessageNoticeRecordServiceImpl extends ServiceImpl<MessageNoticeRecordMapper, MessageNoticeRecord>
    implements MessageNoticeRecordService{

    @Resource
    private NoticeTemplateService noticeTemplateService;
    @Resource
    private ColaClientService colaClientService;

    @Override
    public List<MessageNoticeVo> getTemplateInfo(Integer wechatCustomerId) {
        List<MessageNoticeVo> messageNoticeVos = Lists.newArrayList();
        //用户当前所有通知记录
        List<MessageNoticeRecord> records = baseMapper.selectList(new LambdaQueryWrapper<MessageNoticeRecord>()
                .eq(MessageNoticeRecord::getWechatCustomerId, wechatCustomerId));

        if(CollectionUtils.isEmpty(records)){
            return messageNoticeVos;
        }

        Set<Integer> templateIds = records.stream().map(MessageNoticeRecord::getNoticeTemplateId).collect(Collectors.toSet());

        Map<Integer, List<NoticeTemplate>> templateMap = noticeTemplateService.listByIds(templateIds)
                .stream().collect(Collectors.groupingBy(NoticeTemplate::getId));


        records.forEach(record -> {
            MessageNoticeVo vo = new MessageNoticeVo();
            BeanUtils.copyProperties(record, vo);
            List<NoticeTemplate> orDefault = templateMap.getOrDefault(record.getNoticeTemplateId(), null);
            if(!CollectionUtils.isEmpty(orDefault)){
                BeanUtils.copyProperties(orDefault.get(0), vo);
            }
            messageNoticeVos.add(vo);
        });
        return messageNoticeVos;
    }

    @Override
    public void createRecallNotice(String buCode, String setupId, OrderCallback callback) {
        try{
            MessageNoticeRecord recallRecord = new MessageNoticeRecord();
            recallRecord.setBuCode(buCode);
            recallRecord.setSetupId(setupId);
            recallRecord.setEncryptMobile(callback.getEncryptMobile());
            recallRecord.setWechatCustomerId(callback.getWechatCustomerId());
            recallRecord.setThresholdOrderId(callback.getId());
            NoticeTemplate recallTemplate = noticeTemplateService.getNoticeTemplateId(buCode, setupId, NoticeTypeEnum.RECALL.getType());
            recallRecord.setNoticeTemplateId(recallTemplate.getId());
            recallRecord.setNoticeStatus(MessageNoticeStatusEnum.WAIT.getStatus());
            recallRecord.setNoticeDate(calculateRecallNoticeDate(buCode, setupId));
            this.save(recallRecord);
        }catch (Exception e){
            log.error("创建撤回通知失败,buCode:{},setupId:{},orderCallback:{}", buCode, setupId, callback, e);
        }
    }

    private Date calculateRecallNoticeDate(String buCode, String setupId) {
        GetSetupInfoResponse setupInfo = colaClientService.getSetupInfo(buCode, setupId);
        LocalDateTime now = LocalDateTime.now();
        if(Objects.nonNull(setupInfo)
                && Objects.nonNull(setupInfo.getData())
                && Objects.nonNull(setupInfo.getData().getTo())){
            Date lotteryEndDt = setupInfo.getData().getTo();
            LocalDateTime endDateTime = lotteryEndDt.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();

            Duration duration = Duration.between(now, endDateTime);
            long daysRemaining = duration.toDays();

            LocalDateTime adjustedTime;
            if (daysRemaining > 5) {
                adjustedTime = now.plusDays(5); // now + 5 days
            } else if (daysRemaining > 1) {
                adjustedTime = now.plusDays(1); // now + 1 day
            } else{
                adjustedTime = now.plusMinutes(10); // now + 10 minutes
            }
            return Date.from(adjustedTime.atZone(ZoneId.systemDefault()).toInstant());
        }else{
            throw new RuntimeException("获取活动信息失败");
        }
    }
}




